package hello

import (
	"appengine"
	"net/http"
	"strings"
	"strconv"
	"bytes"
)

func initRecipeFromRequest(r *http.Request) (recipe *Recipe) {
	image, err := saveImage(r, "image")
	panicIfErr(err)
	thumb, err := saveImage(r, "thumb")
	panicIfErr(err)
	description := bytes.NewBufferString(r.FormValue("description")).Bytes()
	sCategoryId := r.FormValue("categoryId")
	var categoryId int64;
	if len(sCategoryId) == 0 {
		categoryId = 0
	} else {
		categoryId = parseInt(sCategoryId)
	}
	recipe = &Recipe{Name: r.FormValue("name"), CategoryId: categoryId, Code: r.FormValue("code"), Description: description, Display: formBool(r.FormValue("display")), Image: image, Thumb: thumb}
	return
}

func actionAdminAddRecipeForm(c *appengine.Context, w http.ResponseWriter, r *http.Request) {
	params := map[string]interface{}{"products": listAllProducts(c), "categories": listAllCategories(c)}
	err := adminTemplates.ExecuteTemplate(w, "editRecipe.html", params)
	panicIfErr(err)
}

func actionAdminEditRecipeForm(c *appengine.Context, w http.ResponseWriter, r *http.Request) {
	recipe, err := getRecipe(c, parseInt(r.FormValue("id")))
	println(recipe)
	notFoundOrPanic(err, w, r)
	println("UNITS:", listAllUnits())
	params := map[string]interface{}{"recipe": recipe, 
		"products": listAllProducts(c),
		"ingredients": listAllIngredients(c, recipe.Id), 
		"units": listAllUnits(),
		"comments": listAllComments(c, recipe.Id),
		"categories": listAllCategories(c)}
	err = adminTemplates.ExecuteTemplate(w, "editRecipe.html", params)
	panicIfErr(err)
}

func actionAdminRecipes(c *appengine.Context, w http.ResponseWriter, r *http.Request) {
	recipes := listAllRecipes(c, false)
	err := adminTemplates.ExecuteTemplate(w, "recipes.html", recipes)
	panicIfErr(err)
}

func actionAdminAddRecipe(c *appengine.Context, w http.ResponseWriter, r *http.Request) {
	key, err := saveRecipe(c, initRecipeFromRequest(r))
	panicIfErr(err)
	if len(r.FormValue("saveAndContinue")) != 0 {
		http.Redirect(w, r, "/admin/editRecipeForm?id="+strconv.FormatInt(key.IntID(), 10), http.StatusFound)
		return
	}
	http.Redirect(w, r, "/admin/recipes", http.StatusFound)
}

func actionAdminUpdateRecipe(c *appengine.Context, w http.ResponseWriter, r *http.Request) {
	id := parseInt(r.FormValue("id"))
	updateRecipe(c, id, initRecipeFromRequest(r))
	if len(r.FormValue("saveAndContinue")) != 0 {
		http.Redirect(w, r, "/admin/editRecipeForm?id="+r.FormValue("id"), http.StatusFound)
		return
	}
	http.Redirect(w, r, "/admin/recipes", http.StatusFound)
}

func actionAdminDeleteRecipe(c *appengine.Context, w http.ResponseWriter, r *http.Request) {
	deleteRecipe(c, parseInt(r.FormValue("id")))
	http.Redirect(w, r, "/admin/recipes", http.StatusFound)
}

func actionAdminAddIngredient(c *appengine.Context, w http.ResponseWriter, r *http.Request) {
	// 'id:name'
	product := r.FormValue("product")
	arr := strings.Split(product, ":")
	productId := parseInt(arr[0])
	productName := arr[1]
	sCount := r.FormValue("count")
	if len(sCount) == 0 {
		// sCount is not specified
		// so make it 0
		sCount = "0";
	}
	ingredient := &Ingredient{Name: productName, Count: parseFloat(sCount), Unit: Unit(parseInt(r.FormValue("unit")))}
	saveIngredient(c, productId, parseInt(r.FormValue("recipeId")), ingredient)
	http.Redirect(w, r, "/admin/editRecipeForm?id="+r.FormValue("recipeId"), http.StatusFound)
}

func actionAdminDeleteIngredient(c *appengine.Context, w http.ResponseWriter, r *http.Request) {
	deleteIngredient(c, parseInt(r.FormValue("id")))
	http.Redirect(w, r, "/admin/editRecipeForm?id="+r.FormValue("recipeId"), http.StatusFound)
}

func actionAdminDeleteRecipeComment(c *appengine.Context, w http.ResponseWriter, r *http.Request) {
	deleteRecipeComment(c, parseInt(r.FormValue("id")))
	http.Redirect(w, r, "/admin/editRecipeForm?id="+r.FormValue("recipeId"), http.StatusFound)
}

func actionAdminAddRecipeComment(c *appengine.Context, w http.ResponseWriter, r *http.Request) {
	comment := &RecipeComment{Text: r.FormValue("text"), Author: r.FormValue("author")}
	saveRecipeComment(c, parseInt(r.FormValue("recipeId")), comment)
	http.Redirect(w, r, "/admin/editRecipeForm?id="+r.FormValue("recipeId"), http.StatusFound)
}